enyo.kind({
    name: "HPITWebService",
	kind: enyo.WebService,
	//* @protected
	constructor: function() {
		this.inherited(arguments);
	},

	makeRequestProps: function(inProps) {
		var delegates = {
			on401: this.on401,
			on0: this.on0,
		};
		var props = this.inherited(arguments);
		return enyo.mixin(delegates, props);
	},
	isFunction: function(object) {
        return typeof object == "function";
    },

	responseSuccess: function(inRequest) {
		if(inRequest.xhr.status == 0 && inRequest.on0){
	        this.error("Received http status 0 connection error. The request url is", inRequest.url);
	        this.dispatchResponse(inRequest.on0, inRequest);
	    } else {
	        this.inherited(arguments);
	    }
		for(var i=0; i< HPITWebService.responders.length;i++){
			if(this.isFunction(HPITWebService.responders[i].onSuccess)){					
				HPITWebService.responders[i].onSuccess(inRequest.response, inRequest);
			}
		}
	},
	responseFailure: function(inRequest) {
	    if(inRequest.didTimeout){
		    this.error("Request times out for URL", inRequest.url);
		} else {
	        if(inRequest.xhr.status == 401){
	    	    this.log("HTTP 401 received, the request URL is ", inRequest.url );
				HPITWebService.lastWebServiceCall = this;
				HPITWebService.lastWebServiceCallParams = inRequest.params;
				if(inRequest.on401){
	                this.dispatchResponse(inRequest.on401, inRequest);
				}
	        } else {
	        	this.inherited(arguments);
		    }
			for(var i=0; i< HPITWebService.responders.length;i++){
				if(this.isFunction(HPITWebService.responders[i].onFailure)){					
					HPITWebService.responders[i].onFailure(inRequest.response, inRequest);
				}
			}
		}
	},
	//register global callbacks
	statics:{
	    responders:[],
		lastWebServiceCall:null,
		lastWebServiceCallParams:null,
		registerGlobalResponder : function(responder){
			HPITWebService.responders.push(responder);
		},
		//In case an Ajax request is saved, it must come from a HTTP 401 error (not authenticated) ==> we resend this request
		resendIfNeeded : function(){
		    if(HPITWebService.lastWebServiceCall && HPITWebService.lastWebServiceCallParams){
			    HPITWebService.lastWebServiceCall.call(HPITWebService.lastWebServiceCallParams);
				HPITWebService.lastWebServiceCall = null;
				HPITWebService.lastWebServiceCallParams = null;
				return true;
			}
			return false;
		}
	}
});